<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #ball {
            position: absolute;
            left: 40px;
            top: 40px;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: black;
        }
    </style>
</head>

<body style="height:2000px ;">
    <input type="button" value="走起" id="btnGo">
    <div id="ball"></div>
    <script>
        let btnGo = document.getElementById('btnGo')
        let ball = document.getElementById('ball')
        let clientWidth
        let clientHeight
        let scrollTop
        let scrollLeft
        window.onload = function () {
            //1.初始化数据
            init();
            //点击让小球动起来
            btnGo.onclick = go;
            //窗口大小改变时
            window.onresize = changeWH;
            //页面滚动时
            window.onscroll = changeScroll;
        }
        let left1 = 40
        let top1 = 40
        let width = 30
        let height = 30
        let directionLeft = 1 //1为正向
        let directionTop = 1
        let step = 2     //每段时间的步数,2
        let timespace = 5 //时间间隔 定时器
        function init() {         
            changeWH() 
            changeScroll()
        }
        function changeWH() {
            clientWidth = document.documentElement.clientWidth || document.body.clientWidth
            clientHeight = document.documentElement.clientHeight || document.body, clientHeight
        }
        function changeScroll() {
            scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft
        }
        function go() {
            setInterval(function () {

                left1 += directionLeft * step
                top1 += directionTop * step

                //2.边界处理
                if (left1 <= 0 + scrollLeft) {

                    directionLeft = 1
                    left1 = 0 + scrollLeft
                } else if (left1 >= clientWidth - width + scrollLeft) {

                    directionLeft = -1
                    left1 = clientWidth - width + scrollLeft
                }
                if (top1 <= 0 + scrollTop) {

                    directionTop = 1
                    top1 = 0 + scrollTop
                } else if (top1 >= clientHeight - height + scrollTop) {

                    directionTop = -1
                    top1 = clientHeight - height + scrollTop
                }

                ball.style.left = left1 + 'px'
                ball.style.top = top1 + 'px'
            }, timespace)
        }
  
    </script>

</body>

</html>